import java.util.EmptyStackException;
import java.util.Stack;



public class Calc {

	public class State {
		public Stack<Double> valueStack = new Stack<Double>();
		public Stack<String> infixExpStack = new Stack<String>();
		boolean isError = false;
	}
	
	private State state;
	
	public Calc() {
		state = new State();
	}
	
	public State process(String expression) {
		for (String tok : expression.split(" ")) {
			if (state.isError)
				return state;
			
			processToken(tok);
		}
//		return state.stack.pop();
		state.isError = state.valueStack.size() > 1 ? true : state.isError;
		return state;
	}
	
	void processToken(String token) {
		try{
		if (token.length() > 0) {
			if (Character.isDigit(token.charAt(0))) {
				Double d = Double.parseDouble(token);
				state.valueStack.push(d);
				state.infixExpStack.push(d.toString());
			}
			else if (token.equals("+")) {
				state.valueStack.push(
					state.valueStack.pop() + 
					state.valueStack.pop());
				
				String second = state.infixExpStack.pop();
				String first = state.infixExpStack.pop();				
				state.infixExpStack.push("("+first +"+" + second+")");
			}
			else if (token.equals("-")) {
				Double second = state.valueStack.pop(); 
				Double first = state.valueStack.pop();
				
				state.valueStack.push(first - second);
				
				String secondStr = state.infixExpStack.pop();
				String firstStr = state.infixExpStack.pop();				
				state.infixExpStack.push("("+firstStr +"-" + secondStr+")");
				
			}
			else if (token.equals("*")) {
				state.valueStack.push(
					state.valueStack.pop() * 
					state.valueStack.pop());
				
				String second = state.infixExpStack.pop();
				String first = state.infixExpStack.pop();				
				state.infixExpStack.push("("+first +"*" + second+")");
			}
			else if (token.equals("/")) {
				Double second = state.valueStack.pop(); 
				Double first = state.valueStack.pop();
				
				state.valueStack.push(first/second);
				
				String secondStr = state.infixExpStack.pop();
				String firstStr = state.infixExpStack.pop();				
				state.infixExpStack.push("("+firstStr +"/" + secondStr+")");
			}
			else if (token.equals("^")) {
				Double second = state.valueStack.pop(); 
				Double first = state.valueStack.pop();
				
				state.valueStack.push(Math.pow(first, second));
				
				String secondStr = state.infixExpStack.pop();
				String firstStr = state.infixExpStack.pop();				
				state.infixExpStack.push("("+firstStr +"^" + secondStr+")");
			}
			else{
				state.isError = true;
				return;
			}
		}
		}
		catch (EmptyStackException ex)
		{
			state.isError = true;
			return;
		}
		

		//dump();
	}
	
	void dump() {
		System.err.print("[ ");
		for (double e : state.valueStack) {
			System.err.print(e + " ");
		}
		System.err.println("]");
	}
	
}

